package com.td.erhome.ui.bughouse;

import android.content.Intent;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.td.erhome.R;
import com.td.erhome.base.BaseActivity;
import com.td.erhome.models.BaseBean;
import com.td.erhome.models.CollectBean;
import com.td.erhome.models.HouseBean;
import com.td.erhome.models.PayMethod;
import com.td.erhome.net.Api;
import com.td.erhome.net.BaseSubscriber;
import com.td.erhome.ui.login.LoginActivity;
import com.td.erhome.utils.ConstUtils;
import com.td.erhome.utils.DialogUtils;
import com.td.erhome.utils.DisplayUtil;
import com.td.erhome.utils.GlideImageLoader;
import com.td.erhome.utils.ImageLoader;
import com.td.erhome.utils.PayUtils;
import com.td.erhome.utils.RxBus;
import com.td.erhome.utils.T;
import com.td.erhome.utils.UserManager;
import com.td.erhome.widget.ListenedScrollView;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.listener.OnBannerListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

public class HouseInfoActivity extends BaseActivity {

    @Bind(R.id.banner)
    Banner mBanner;
    @Bind(R.id.img_share)
    ImageView mImgShare;
    @Bind(R.id.img_collect)
    ImageView mImgCollect;
    @Bind(R.id.tv_get_info)
    TextView mTvGetInfo;
    @Bind(R.id.tv_only_house)
    TextView mTvOnlyHouse;
    @Bind(R.id.tv_jsdk)
    TextView mTvJsdk;
    @Bind(R.id.tv_info_name)
    TextView mTvInfoName;
    @Bind(R.id.tv_info_house_type)
    TextView mTvInfoHouseType;
    @Bind(R.id.tv_info_acreage)
    TextView mTvInfoAcreage;
    @Bind(R.id.tv_info_amount)
    TextView mTvInfoAmount;
    @Bind(R.id.tv_info_price)
    TextView mTvInfoPrice;
    @Bind(R.id.img_tx)
    ImageView mImgTx;
    @Bind(R.id.tv_info_orientation)
    TextView mTvInfoOrientation;
    @Bind(R.id.tv_info_id)
    TextView mTvInfoId;
    @Bind(R.id.tv_info_floor)
    TextView mTvInfoFloor;
    @Bind(R.id.tv_info_decoration)
    TextView mTvInfoDecoration;
    @Bind(R.id.tv_true_name)
    TextView mTvTrueName;
    @Bind(R.id.img_back)
    ImageView mImgBack;
    @Bind(R.id.tv_info_ancillary_facilities)
    TextView mTvInfoAncillaryFacilities;
    @Bind(R.id.lin_add_view)
    LinearLayout mLinAddView;
    @Bind(R.id.tv_more)
    TextView mTvMore;
    @Bind(R.id.re_alpha)
    LinearLayout mReAlpha;
    @Bind(R.id.scrollView)
    ListenedScrollView scrollView;

    private DialogUtils mDialogUtils;
    private HouseBean.SellHouseListBean mSellHouseListBean;
    private Subscription mSubscribe;
    private Subscription mSubscribe1;
    private DisplayMetrics displayMetrics;
    private float density;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_house_info;
    }
    @Override
    protected void initView() {

        //获取当前手机屏幕的像素密度比例
        displayMetrics = getResources().getDisplayMetrics();
        density = displayMetrics.density;

        /*if (Build.VERSION.SDK_INT >= 21) {
            View decorView = getWindow().getDecorView();
            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            decorView.setSystemUiVisibility(option);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }*/
        mDialogUtils = new DialogUtils();
        mSellHouseListBean = (HouseBean.SellHouseListBean) getIntent().getSerializableExtra("SellHouseListBean");

        upDataBanner(mSellHouseListBean);
        addFacilitiesImg(mLinAddView,mSellHouseListBean.house_tag);

        String is_buy_ok = mSellHouseListBean.is_buy_ok;

        if (is_buy_ok==null){
            mTvGetInfo.setText("付费获取房主信息");
        }else {
            mTvGetInfo.setText(mSellHouseListBean.is_buy_ok.equals("2")?"付费获取房主信息":"显示房主信息");
        }

        if (UserManager.getIns().getUser()!=null){
            postData();
        }

        mSubscribe = RxBus.getInstance().toObserverable(PayMethod.class)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<PayMethod>() {
                    @Override
                    public void call(PayMethod payMethod) {
                        getSellerInfo(payMethod.pay_type);
                    }
                });

        mSubscribe1 = RxBus.getInstance().toObserverable(Integer.class)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<Integer>() {
                    @Override
                    public void call(Integer i) {
                        if (i== ConstUtils.FINISH_CON);
                        mDialogUtils.initPopShowInfo(HouseInfoActivity.this,mSellHouseListBean);
                        mSellHouseListBean.is_buy_ok="1";
                        mTvGetInfo.setText("显示房主信息");
                    }
                });

        mReAlpha.getBackground().setAlpha(0);

        scrollView.setOnScrollListener(new ListenedScrollView.OnScrollListener() {
            @Override
            public void onBottomArrived() { //滑到底部

            }

            @Override
            public void onScrollStateChanged(ListenedScrollView view, int scrollState) {

            }

            @Override
            public void onScrollChanged(int l, int t, int oldl, int oldt) {
                Log.i("4654654646",l+"-------"+t+"------");

                mReAlpha.getBackground().setAlpha(t>510?255:t/2);

            }
        });
    }

    private void addFacilitiesImg(LinearLayout linearLayout , List<String> house_tag) {
        for (int i=0 ; i<house_tag.size() ; i++){
            String s = house_tag.get(i);
            TextView textView = new TextView(this);

            LinearLayout.LayoutParams layoutParams =
                    new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            //设置居中显示：
            layoutParams.gravity = Gravity.CENTER;
            //设置它的上下左右的margin
            layoutParams.setMargins((int)(4* density) , 0 , (int)(4* density) , 0);

            textView.setLayoutParams(layoutParams);
            textView.setTextColor(getResources().getColor(R.color.color_048d99));
            textView.setBackgroundResource(R.drawable.shape_status);
            textView.setPadding((int)(5* density) , (int)(3* density) , (int)(5* density) , (int)(3* density));
            textView.setText(s);
            textView.setTextSize(DisplayUtil.px2sp(this,34));
            linearLayout.addView(textView);
        }

        //   linearLayout.setPadding(0 , (int)(10* density) , 0 , (int)(10* density));
    }


    @Override
    protected void releaseResource() {
        mDialogUtils = null;
        if (!mSubscribe.isUnsubscribed()){
            mSubscribe.unsubscribe();
        } if (!mSubscribe1.isUnsubscribed()){
            mSubscribe1.unsubscribe();
        }
        mReAlpha.getBackground().setAlpha(255);
    }

    @Override
    public void onBackPressed() {
        mReAlpha.getBackground().setAlpha(255);
        finish();

    }

    //获取支付信息
    public void getSellerInfo(String pay_type){
        PayUtils payUtils = new PayUtils(this);
        HashMap<String, Object> params = new HashMap<>();
        params.put("house_id", mSellHouseListBean.id);
        params.put("pay_type",pay_type);
        params.put("user_id", UserManager.getIns().getUser().uid);
        payUtils.getSellerInfo(params);
    }

    @OnClick({R.id.img_share, R.id.img_collect, R.id.tv_get_info,R.id.img_back})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.img_share:
                mDialogUtils.createTopUp(this, mTvGetInfo,"四方腾达",mSellHouseListBean.house_detail_url,"看二手房就来四方腾达");
                break;
            case R.id.img_collect:
                if (UserManager.getIns().getUser()==null){
                    Intent intent1 = new Intent(this, LoginActivity.class);
                    startActivity(intent1);
                    return;
                }
                if (mSellHouseListBean.is_favorite.equals("1")) {
                    cancelFavorite();
                }
                else if (mSellHouseListBean.is_favorite.equals("2"))  {
                    addToFavorite();
                }
                break;
            case R.id.tv_get_info:
                if (UserManager.getIns().getUser()==null){
                    Intent intent1 = new Intent(this, LoginActivity.class);
                    startActivity(intent1);
                    return;
                }
                if (mSellHouseListBean.is_buy_ok.equals("2"))
                    mDialogUtils.initPopGetInfo(this, 1);
                else mDialogUtils.initPopShowInfo(HouseInfoActivity.this,mSellHouseListBean);
                break;
            case R.id.img_back:
                mReAlpha.getBackground().setAlpha(255);
                finish();
                break;

        }
    }

    private void upDataBanner(HouseBean.SellHouseListBean mSellHouseListBean) {
        mTvInfoName.setText(mSellHouseListBean.district_name);
        mTvInfoHouseType.setText(mSellHouseListBean.type_of_rooms+"室"+mSellHouseListBean.type_of_hall+"厅"+mSellHouseListBean.type_of_guards+"卫");
        mTvInfoAcreage.setText(mSellHouseListBean.house_dimensions+"㎡");
        mTvInfoAmount.setText(mSellHouseListBean.sell_amount+"万");
        mTvInfoPrice.setText(mSellHouseListBean.average_price+"元/㎡");
        // mTvInfoFirstAmount.setText(); 首付
        // mTvInfoMonthPrice.setText(); 首付  mImgTx
        mTvTrueName.setText(mSellHouseListBean.true_name.substring(0,1)+"**\n购房时间 : "+mSellHouseListBean.house_buy_time);
        ImageLoader.loadCicleImage(this,mSellHouseListBean.seller_head_img,R.mipmap.td_min_tx,mImgTx);
        mTvOnlyHouse.setText(mSellHouseListBean.is_only_housing);
        mTvJsdk.setText(mSellHouseListBean.is_accept_buyer_loan);
        mTvInfoOrientation.setText(mSellHouseListBean.orientation_of_house);
        mTvInfoId.setText(mSellHouseListBean.id);
        mTvInfoFloor.setText("第"+mSellHouseListBean.house_floor+"层--总共"+mSellHouseListBean.total_floor+"层");
        mTvMore.setText(mSellHouseListBean.house_owner_remark);
        mTvInfoDecoration.setText(mSellHouseListBean.house_decoration_type);
        mTvInfoAncillaryFacilities.setText(mSellHouseListBean.ancillary_facilities_name.toString().substring(1,mSellHouseListBean.ancillary_facilities_name.toString().length()-1));
        mImgCollect.setImageResource(mSellHouseListBean.is_favorite.equals("1")?R.mipmap.ysc: R.mipmap.td_xh);
        final ArrayList<String> mList = new ArrayList<>();
        for (int i = 0; i < mSellHouseListBean.house_image_list.size(); i++) {
            mList.add(mSellHouseListBean.house_image_list.get(i).house_image);
        }
        mBanner.isAutoPlay(false);
        mBanner.setBannerStyle(BannerConfig.NUM_INDICATOR);
        mBanner.setIndicatorGravity(BannerConfig.LEFT);//指示器左
        mBanner.setImages(mList).setImageLoader(new GlideImageLoader()).start();
        mBanner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {
                Intent intent = new Intent(HouseInfoActivity.this, PhotoActivity.class);
                intent.putExtra("num", position + 1);
                intent.putStringArrayListExtra("infoList", mList);
                startActivity(intent);
            }
        });
    }
    //上传浏览记录
    public void postData(){
        HashMap<String, Object> params = new HashMap<>();
        params.put("user_id", UserManager.getIns().getUser().uid+"");
        params.put("house_id", mSellHouseListBean.id);
        Api.getRetrofit().saveReviewInfo(params)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<BaseBean>(HouseInfoActivity.this){
                    @Override
                    public void onStart() {
                    }
                    @Override
                    public void onNext(BaseBean baseBean) {
                        super.onNext(baseBean);
                    }
                });

    }

    //收藏
    private void addToFavorite() {
        HashMap<String, Object> params = new HashMap<>();
        params.put("user_id", UserManager.getIns().getUser().uid+"");
        params.put("house_id", mSellHouseListBean.id);
        Api.getRetrofit().addToFavorite(params)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<BaseBean>(HouseInfoActivity.this){
                    @Override
                    public void onNext(BaseBean houseBeanBaseBean) {
                        super.onNext(houseBeanBaseBean);
                        T.showLong(HouseInfoActivity.this,"收藏成功");
                        mImgCollect.setImageResource(R.mipmap.ysc);
                        mSellHouseListBean.is_favorite = "1";
                        RxBus.getInstance().post(new CollectBean(1));
                    }
                });
    }

    //取消收藏
    private void cancelFavorite() {
        HashMap<String, Object> params = new HashMap<>();
        params.put("user_id", UserManager.getIns().getUser().uid+"");
        params.put("house_id", mSellHouseListBean.id);
        Api.getRetrofit().cancelFavorite(params)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<BaseBean>(HouseInfoActivity.this){
                    @Override
                    public void onNext(BaseBean houseBeanBaseBean) {
                        super.onNext(houseBeanBaseBean);
                        T.showLong(HouseInfoActivity.this,"已取消收藏");
                        mImgCollect.setImageResource(R.mipmap.td_xh);
                        mSellHouseListBean.is_favorite = "2";
                        RxBus.getInstance().post(new CollectBean(2));

                    }
                });
    }

}
